export default {
  // 为当前模块开启命名空间
  namespaced: true,

  // 模块的 state 数据
  state: () => ({
    cart: uni.getStorageSync('cart') || []
  }),

  // 模块的 mutations 方法
  mutations: {
    updateAllGoodsState(state, newState) {
      state.cart.forEach(t => t.goods_state = newState)
      uni.setStorageSync('cart', state.cart)
    },
    addToCart(state, goods) {
      let f = state.cart.find(t => t.goods_id === goods.goods_id)
      if (!f) {
        state.cart.push(goods)
      } else {
        f.goods_count++
      }
      uni.setStorageSync('cart', state.cart)
    },
    updateGoodsState(state, {
      goods_id,
      goods_state
    }) {
      let f = state.cart.find(t => t.goods_id === goods_id)
      if (f) {
        f.goods_state = goods_state
      }
      uni.setStorageSync('cart', state.cart)
    },
    updateGoodsCount(state, {
      goods_id,
      goods_count
    }) {
      let f = state.cart.find(t => t.goods_id === goods_id)
      if (f) {
        f.goods_count = goods_count
      }
      uni.setStorageSync('cart', state.cart)
    },
    removeGoodsById(state, goods_id) {
      state.cart = state.cart.filter(t => t.goods_id !== goods_id)
      console.log(state.cart)
      uni.setStorageSync('cart', state.cart)
    }
  },

  // 模块的 getters 属性
  getters: {
    total(state) {
      return state.cart.reduce((total, item) => total + item.goods_count, 0)
    },
    checkedCount: (state) => state.cart.filter(t => t.goods_state === true).reduce((total, item) => total + item
      .goods_count, 0),
    checkedGoodsAmount: (state) => state.cart.filter(t => t.goods_state === true).reduce((total, item) => total + item
      .goods_count * item.goods_price, 0)
      .toFixed(2)
  },
}
